// 音频上传和动态显示功能（后端服务器版本）
export function initUploadFeature() {
  const MAX_FILE_SIZE = 20 * 1024 * 1024;  // 20MB
  const API_BASE = '/api';

  // 获取认证令牌
  function getAuthToken() {
    try {
      const userData = localStorage.getItem('voice_community_user');
      if (userData) {
        const user = JSON.parse(userData);
        return user.token;
      }
    } catch (error) {
      console.error('获取认证令牌失败:', error);
    }
    return null;
  }

  // 检查权限
  function checkPermission(action) {
    try {
      const userData = localStorage.getItem('voice_community_user');
      if (userData) {
        const user = JSON.parse(userData);
        if (user.role === 'admin') {
          return true;
        }
      }
    } catch (error) {
      console.error('检查权限失败:', error);
    }
    return false;
  }

  // 页面加载时获取已有的音频列表
  loadAudioList();

  // 上传按钮点击事件
  document.getElementById('upload-btn').addEventListener('click', handleUpload);

  // 删除按钮事件委托
  document.getElementById('audio-list').addEventListener('click', (e) => {
    if (e.target.classList.contains('delete-btn')) {
      const packageId = e.target.getAttribute('data-package-id');
      deleteAudioPackage(packageId);
    }
  });

  // 从服务器加载音频列表
  async function loadAudioList() {
    try {
      showStatus('正在加载音频列表...', 'info');
      
      const response = await fetch(`${API_BASE}/audio-list`);
      const result = await response.json();
      
      if (result.success) {
        const audioList = result.data;
        
        // 清空现有列表（保留默认示例）
        const tbody = document.getElementById('audio-list');
        // 只保留默认示例（data-sample-id以demo开头的）
        const rows = tbody.querySelectorAll('tr');
        rows.forEach(row => {
          const sampleId = row.getAttribute('data-sample-id');
          if (sampleId && !sampleId.startsWith('demo')) {
            row.remove();
          }
        });
        
        // 添加服务器上的音频
        audioList.forEach(audioPackage => {
          addAudioRowFromServer(audioPackage);
        });
        
        updateSampleCount();
        
        // 重新初始化音频控制
        reinitAudioControls();
        
        console.log(`已加载 ${audioList.length} 个音频包`);
        hideStatus();
      } else {
        showStatus('加载音频列表失败', 'error');
      }
    } catch (error) {
      console.error('加载音频列表失败:', error);
      showStatus('无法连接到服务器，请确保后端服务已启动', 'error');
    }
  }

  // 处理上传
  async function handleUpload() {
    // 检查权限
    if (!checkPermission('upload')) {
      showStatus('❌ 需要管理员权限才能上传音频', 'error');
      return;
    }

    const packageName = document.getElementById('audio-package-name').value.trim();
    const originFile = document.getElementById('origin-audio').files[0];
    const basicFile = document.getElementById('basic-audio').files[0];
    const advanceFile = document.getElementById('advance-audio').files[0];

    // 验证输入
    if (!packageName) {
      showStatus('请输入音频包名称', 'error');
      return;
    }

    if (!originFile || !basicFile || !advanceFile) {
      showStatus('请选择所有三个音频文件', 'error');
      return;
    }

    // 验证文件大小
    if (!validateFileSize([originFile, basicFile, advanceFile])) {
      return;
    }

    // 验证文件类型
    const validExtensions = ['.wav', '.mp3'];
    const files = [originFile, basicFile, advanceFile];
    for (let file of files) {
      const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
      if (!validExtensions.includes(ext)) {
        showStatus(`文件"${file.name}"格式不正确，请上传WAV或MP3格式`, 'error');
        return;
      }
    }

    // 创建FormData
    const formData = new FormData();
    formData.append('packageName', packageName);
    formData.append('origin', originFile);
    formData.append('basic', basicFile);
    formData.append('advance', advanceFile);

    // 显示上传进度
    showStatus('正在上传音频文件...', 'info');
    
    // 禁用上传按钮
    const uploadBtn = document.getElementById('upload-btn');
    uploadBtn.disabled = true;
    uploadBtn.textContent = '上传中...';

    try {
      const token = getAuthToken();
      const headers = {};
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      const response = await fetch(`${API_BASE}/upload-audio-package`, {
        method: 'POST',
        headers: headers,
        body: formData
      });

      const result = await response.json();

      if (result.success) {
        // 上传成功，添加到表格
        addAudioRowFromServer(result.data);

        // 清空输入
        document.getElementById('audio-package-name').value = '';
        document.getElementById('origin-audio').value = '';
        document.getElementById('basic-audio').value = '';
        document.getElementById('advance-audio').value = '';

        showStatus(`✅ 成功上传音频包：${packageName}`, 'success');

        // 更新样本计数
        updateSampleCount();

        // 重新初始化音频控制
        reinitAudioControls();

        // 滚动到新添加的行
        setTimeout(() => {
          const newRow = document.querySelector(`tr[data-package-id="${result.data.id}"]`);
          if (newRow) {
            newRow.scrollIntoView({ behavior: 'smooth', block: 'center' });
          }
        }, 100);
      } else {
        showStatus(`❌ 上传失败：${result.message}`, 'error');
      }
    } catch (error) {
      console.error('上传失败:', error);
      showStatus('❌ 上传失败，请检查网络连接和后端服务', 'error');
    } finally {
      // 恢复上传按钮
      uploadBtn.disabled = false;
      uploadBtn.textContent = '添加到对比列表';
    }
  }

  // 验证文件大小
  function validateFileSize(files) {
    for (let file of files) {
      if (file.size > MAX_FILE_SIZE) {
        const sizeMB = (file.size / 1024 / 1024).toFixed(2);
        const maxSizeMB = (MAX_FILE_SIZE / 1024 / 1024).toFixed(0);
        showStatus(`文件"${file.name}"过大 (${sizeMB}MB)，单个文件不能超过${maxSizeMB}MB`, 'error');
        return false;
      }
    }
    return true;
  }

  // 从服务器数据添加音频行
  function addAudioRowFromServer(audioPackage) {
    const tbody = document.getElementById('audio-list');
    const row = document.createElement('tr');
    row.className = 'hover:bg-gray-50';
    row.setAttribute('data-package-id', audioPackage.id);

    // 格式化上传时间
    const uploadTime = new Date(audioPackage.uploadTime).toLocaleString('zh-CN');

    row.innerHTML = `
      <td class="border border-gray-200 px-4 py-3">
        <div class="font-medium text-gray-900">${escapeHtml(audioPackage.name)}</div>
        <div class="text-xs text-gray-500 mt-1">上传时间: ${uploadTime}</div>
      </td>
      <td class="border border-gray-200 px-4 py-3">
        <div class="audio-player">
          <div class="audio-controls">
            <button class="audio-play-btn" data-audio="${audioPackage.files.origin.path}" data-sample="${audioPackage.id}" data-type="original">
              <span class="play-icon">▶</span>
            </button>
            <button class="audio-mute-btn" data-audio="${audioPackage.files.origin.path}" title="静音">
              <span class="mute-icon">🔊</span>
            </button>
          </div>
          <div class="audio-time-display">
            <span class="current-time">0:00</span> / <span class="total-time">0:00</span>
          </div>
        </div>
      </td>
      <td class="border border-gray-200 px-4 py-3">
        <div class="audio-player">
          <div class="audio-controls">
            <button class="audio-play-btn" data-audio="${audioPackage.files.basic.path}" data-sample="${audioPackage.id}" data-type="basic">
              <span class="play-icon">▶</span>
            </button>
            <button class="audio-mute-btn" data-audio="${audioPackage.files.basic.path}" title="静音">
              <span class="mute-icon">🔊</span>
            </button>
          </div>
          <div class="audio-time-display">
            <span class="current-time">0:00</span> / <span class="total-time">0:00</span>
          </div>
        </div>
      </td>
      <td class="border border-gray-200 px-4 py-3">
        <div class="audio-player">
          <div class="audio-controls">
            <button class="audio-play-btn" data-audio="${audioPackage.files.advance.path}" data-sample="${audioPackage.id}" data-type="advanced">
              <span class="play-icon">▶</span>
            </button>
            <button class="audio-mute-btn" data-audio="${audioPackage.files.advance.path}" title="静音">
              <span class="mute-icon">🔊</span>
            </button>
          </div>
          <div class="audio-time-display">
            <span class="current-time">0:00</span> / <span class="total-time">0:00</span>
          </div>
        </div>
      </td>
      <td class="border border-gray-200 px-4 py-3 text-center">
        <button class="delete-btn text-red-500 hover:text-red-700 text-sm font-medium" data-package-id="${audioPackage.id}">
          删除
        </button>
      </td>
    `;

    tbody.appendChild(row);
  }

  // 删除音频包
  async function deleteAudioPackage(packageId) {
    // 检查权限
    if (!checkPermission('delete')) {
      showStatus('❌ 需要管理员权限才能删除音频', 'error');
      return;
    }

    if (!confirm('确定要删除这个音频包吗？此操作不可撤销。')) {
      return;
    }

    try {
      showStatus('正在删除...', 'info');
      
      const token = getAuthToken();
      const headers = {};
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
      
      const response = await fetch(`${API_BASE}/audio-package/${packageId}`, {
        method: 'DELETE',
        headers: headers
      });

      const result = await response.json();

      if (result.success) {
        // 从DOM中移除
        const row = document.querySelector(`tr[data-package-id="${packageId}"]`);
        if (row) {
          row.remove();
        }

        showStatus('✅ 已删除音频包', 'success');
        updateSampleCount();
      } else {
        showStatus(`❌ 删除失败：${result.message}`, 'error');
      }
    } catch (error) {
      console.error('删除失败:', error);
      showStatus('❌ 删除失败，请检查网络连接', 'error');
    }
  }

  // 更新样本计数显示
  function updateSampleCount() {
    const currentCount = document.getElementById('audio-list').querySelectorAll('tr').length;
    const sampleCountElement = document.getElementById('sample-count');
    
    if (sampleCountElement) {
      sampleCountElement.textContent = currentCount;
      
      // 根据数量改变颜色提示
      if (currentCount >= 40) {
        sampleCountElement.className = 'font-bold text-red-600';
      } else if (currentCount >= 25) {
        sampleCountElement.className = 'font-bold text-yellow-600';
      } else {
        sampleCountElement.className = 'font-bold text-green-600';
      }
    }
  }

  // 显示状态消息
  function showStatus(message, type) {
    const statusDiv = document.getElementById('upload-status');
    statusDiv.className = 'mt-4 text-sm p-3 rounded';
    statusDiv.classList.remove('hidden');

    if (type === 'success') {
      statusDiv.className += ' bg-green-100 text-green-800 border border-green-200';
    } else if (type === 'error') {
      statusDiv.className += ' bg-red-100 text-red-800 border border-red-200';
    } else {
      statusDiv.className += ' bg-blue-100 text-blue-800 border border-blue-200';
    }

    statusDiv.textContent = message;

    // 成功和错误消息3秒后自动隐藏
    if (type === 'success' || type === 'error') {
      setTimeout(() => {
        statusDiv.classList.add('hidden');
      }, 3000);
    }
  }

  // 隐藏状态消息
  function hideStatus() {
    const statusDiv = document.getElementById('upload-status');
    statusDiv.classList.add('hidden');
  }

  // HTML转义
  function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }

  // 重新初始化音频控制
  function reinitAudioControls() {
    // 触发自定义事件，让audio.js重新绑定事件
    const event = new CustomEvent('audio-controls-update');
    document.dispatchEvent(event);
  }

  console.log('音频上传功能已初始化（后端服务器模式）');
  console.log(`API地址: ${API_BASE}`);
  console.log(`上传限制: 单个文件不超过${MAX_FILE_SIZE / 1024 / 1024}MB`);
}
